#include <stdio.h>

int main(void) {
    float a = 0.1;
    // 做如下比较的时候 a 是单精度浮点数类型即float，而字面量 0.1 在C和C++中是双精度浮点数类型即double
    // 这两者在内存中表示0.1的时候都会发生精度损失，但是双精度比单精度更靠近0.1， 虽然他们都比实际的0.1要大
    if (a > 0.1) {
        printf("float a is greater than 0.1\n"); // 输出这个大于
    } else if (a < 0.1) {
        printf("float a is less than 0.1\n");
    } else {
        printf("float a is equal to 0.1\n");
    }

    if (a - 0.1 > 0) {
        printf("float a - 0.1 is greater than 0\n");// 输出这个大于
    } else if (a - 0.1 < 0) {
        printf("float a - 0.1 is less than 0\n");
    } else {
        printf("float a - 0.1 is equal to 0\n");
    }

    double b = 0.1;
    // 当我们使用双精度浮点数类型即double时，字面量0.1因为也是双精度浮点数类型，所以二者的二进制是一模一样的，虽然都会发生一样的精度损失。
    if (b > 0.1) {
        printf("double b is greater than 0.1\n");
    } else if (b < 0.1) {
        printf("double b is less than 0.1\n");
    } else {
        printf("double b is equal to 0.1\n");// 输出这个相等
    }
    if (b - 0.1 > 0) {
        printf("double b - 0.1 is greater than 0\n");
    } else if (b - 0.1 < 0) {
        printf("double b - 0.1 is less than 0\n");
    } else {
        printf("double b - 0.1 is equal to 0\n");// 输出这个相等
    }

}

// Usage: gcc -o minus0.1.out minus0.1.c && ./minus0.1.out
// Output: a is greater than 0.1
// Explanation: The output is unexpected because of the way floating-point numbers are represented in memory.
// The value 0.1 cannot be represented exactly in binary, leading to small precision errors.
// To avoid this issue, we can use a tolerance value to compare floating-point numbers.
// Corrected code:
/**
#include <stdio.h>
#include <math.h>
#include <stdbool.h>
#define EPSILON 0.00001
bool are_equal(float a, float b) {
    return fabs(a - b) < EPSILON;
}
int main(void) {
    float a = 0.1;
    if (are_equal(a, 0.1)) {
        printf("a is equal to 0.1\n");
    } else if (a > 0.1) {
        printf("a is greater than 0.1\n");
    } else {
        printf("a is less than 0.1\n");
    }
}
*/
